# -*- coding: utf-8 -*-

from git.repo import Repo
from com.maycur import config_loader
from com.maycur.git.base.git_operation import GitOperation

from com.maycur.utils import CommonUtils
from conf.entity.module.git_config import TagOperateType


def try_manage_tags():
    # 获取配置，打印待处理仓库统计数据
    git_config = config_loader.get_git_config()
    tag_config = git_config.tag_config
    if tag_config is None:
        print('tag config not found, do nothing')
        return
    if not tag_config.do_operate:
        print('tag switch is off, do nothing')
        return
    tag_op_type = tag_config.operate_type
    if tag_op_type is None:
        return

    project_count = 0
    for branch_pair in git_config.branch_pairs:
        project_count = project_count + len(branch_pair.projects)
    print(f'>>> there are {project_count} projects to handle <<<')

    # 存放所有结果
    tag_operated_projects = []
    tag_no_operation_projects = []

    for branch_pair in git_config.branch_pairs:
        print(f'\nstart processing branch pair: {branch_pair.pair_name} ...')
        print('========================================================================')

        for project in branch_pair.projects:
            print(f'start processing project: [{project.name}] ...')
            repo = Repo(project.project_path)

            git_operation = GitOperation(repo, project)

            # Step 1, 检查本地仓库是否有未提交的修改，如果有，先暂存起来
            git_operation.stash_if_possible()

            # Step 2, 尝试操作目标tag，并推送到远程仓库
            if tag_op_type == TagOperateType.C:
                git_operation.create_tag(project, branch_pair.down_branch, tag_config.name, tag_config.comment)
            elif tag_op_type == TagOperateType.D:
                git_operation.delete_tag(project, tag_config.name)

            # Step 3, 统计单个项目tag操作结果
            if project.tag_operated:
                tag_operated_projects.append(project)
            else:
                tag_no_operation_projects.append(project)

            # Step 4, 如果合并过程中将工作区暂存了，执行stash pop操作
            git_operation.pop_stash_if_possible()

            print('------------------------------------------------------------------------')

    # Step 5, 统计所有项目tag操作结果
    statics_log_min_len = 40
    start_log = f'\n\n=====Tag操作情况如下'
    print(CommonUtils.r_padding(start_log, statics_log_min_len, '='))
    if len(tag_no_operation_projects) > 0:
        print(CommonUtils.r_padding(f'=====[以下服务({len(tag_no_operation_projects)})Tag{tag_op_type.value}失败]',
                                    statics_log_min_len, '='))
        for item in tag_no_operation_projects:
            print(item.name)
    if len(tag_operated_projects) > 0:
        print(CommonUtils.r_padding(f'=====[以下服务({len(tag_operated_projects)})Tag{tag_op_type.value}成功]',
                                    statics_log_min_len, '='))
        for item in tag_operated_projects:
            print(item.name)


if __name__ == '__main__':
    try_manage_tags()
